<template>
  <div class="add-good">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert center title="添加商品信息" :closable="false" type="info" show-icon></el-alert>
      <el-steps align-center :active="activeIndex" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="goodForm"
        :rules="goodRule"
        ref="goodForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :before-leave="leaveTab"
          tab-position="left"
          v-model="activeName"
          @tab-click="changeTab"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="goodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="goodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="goodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                @change="cateChange"
                v-model="cateIdKeys"
                :options="cateList"
                :props="addOptions"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item v-for="(item,index) in paramList" :key="index" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(attr,index) in item.attr_vals"
                  :key="index"
                  :label="attr"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item
              :label="item.attr_name"
              v-for="(item,index) in attributeList"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              :action="baseImgUrl"
              :on-preview="picPreview"
              :on-remove="picRemove"
              :on-success="uploadSuccess"
              :file-list="picList"
              :headers="headersObj"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor v-model="goodForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="submitGood" style="margin:20px;">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="dialogPicVisible" width="50%">
      <img :src="pic" alt class="uploadImg" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: 0, // 当前所在步骤
      activeName: '', // 当前tab名称
      goodForm: {
        goods_name: '', // 商品名称
        goods_price: '', // 商品价格
        goods_weight: '', // 商品重量
        goods_number: '', // 商品数量
        goods_cat: '', // 商品分类列表
        goods_introduce: '', // 商品介绍
        pics: [], // 图片列表
        attrs: [] // 商品参数
      },
      addOptions: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      goodRule: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      cateList: [], // 商品分类
      cateIdKeys: [], // 下拉列表选中项
      checkParamList: [], // 动态参数
      cateId: 0, // 分类参数id
      paramList: [], // 动态参数列表
      attributeList: [], // 静态属性
      paramName: '', // 动态参数名
      baseImgUrl: 'http://127.0.0.1:8888/api/private/v1/upload', // 图片地址
      picList: [], // 上传的文件列表
      // 设置文件上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      dialogPicVisible: false, // 图片预览弹窗
      pic: '' // 预览图片路径
    }
  },
  created() {
    this.getCates()
  },
  methods: {
    changeTab() {
      this.activeIndex = Number(this.activeName)
      if (this.activeName === '1') {
        this.getParamList()
      } else if (this.activeName === '2') {
        this.getAttributeList()
      }
    },
    async getCates() {
      const { data: res } = await this.$axios.get('categories', {
        params: { type: 3 }
      })

      if (res.meta.status !== 200) return this.$message.error('商品分类获取失败')
      this.cateList = res.data
    },
    cateChange() {
      if (this.cateIdKeys.length !== 3) {
        this.cateIdKeys = []
        return
      }
      this.cateId = this.cateIdKeys[2]
      // 添加到商品form表单中
      this.goodForm.goods_cat = this.cateIdKeys.join(',')
    },
    leaveTab(activeName, oldActiveName) {
      if (this.cateIdKeys.length !== 3 && oldActiveName === '0') {
        this.activeName = '0'
        this.$message.error('请选择商品分类')
        return false
      }
    },

    // 获取动态参数
    async getParamList() {
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: 'many'
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
      })
      this.paramList = !res.data ? [] : res.data
    },
    // 获取静态属性
    async getAttributeList() {
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: 'only'
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.attributeList = !res.data ? [] : res.data
    },

    // 文件列表中已上传的文件的钩子
    picPreview(file) {
      this.pic = file.response.data.url
      this.dialogPicVisible = true
    },
    // 文件列表移除文件的钩子
    picRemove(file, feilList) {
      // file 删除的文件临时路径，fileList : 现有的文件列表
      // 删除临时存储中的临时路径
      let index = this.goodForm.pics.findIndex((item, index) => {
        return item.pic === file.response.data.tmp_path
      })
      this.goodForm.pics.splice(index, 1)
    },
    uploadSuccess(response, file, fileList) {
      let picObj = {
        pic: response.data.tmp_path
      }
      if (response.meta.status === 200) {
        this.goodForm.pics.push(picObj)
      }
    },
    // 添加商品
    submitGood() {
      this.$refs.goodForm.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的数据')
        console.log(this.paramList)
        console.log(this.attributeList)
        this.paramList.forEach((item, index) => {
          const parObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals[index]
          }
          this.goodForm.attrs.push(parObj)
        })
        this.attributeList.forEach((item, index) => {
          const attObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.goodForm.attrs.push(attObj)
        })
        const { data: res } = await this.$axios.post('goods', this.goodForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.$route.path('/goods')
      })
    }
  },
  computed: {},
  filters: {
    attrArr(val) {
      if (!val) return
      return val.split(' ')
    }
  },
  watch: {}
}
</script>

<style lang='less' scoped>
.uploadImg {
  width: 100%;
}
</style>
